package com.lzk.jetpacktest.workmanager

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.work.*
import com.lzk.jetpacktest.R
import com.lzk.jetpacktest.databinding.ActivityWorkManagerBinding
import kotlinx.coroutines.suspendCancellableCoroutine
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class WorkManagerActivity : AppCompatActivity() {
    private lateinit var mBinding: ActivityWorkManagerBinding

    private val mWorkerManager = WorkManager.getInstance()
    private val mLiveWorker: LiveData<List<WorkInfo>> = mWorkerManager.getWorkInfosByTagLiveData(
        WORKER_TAG)
    private var mWorkInfo: WorkInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_work_manager)
        initEvent()
    }

    private fun initEvent(){
        mBinding.goBtn.setOnClickListener {
            mWorkInfo?.let {
                when(it.state){
                    WorkInfo.State.CANCELLED,
                    WorkInfo.State.FAILED -> {
                        doWorker()
                    }
                    WorkInfo.State.SUCCEEDED -> {
                        Toast.makeText(this,"worker completed",Toast.LENGTH_SHORT).show()
                    }
                    else -> {
                        Toast.makeText(this,"worker running",Toast.LENGTH_SHORT).show()
                    }
                }
            }?: doWorker()
        }

        mBinding.cancelBtn.setOnClickListener {
            cancelWorker()
        }

        //接收worker的状态
        mLiveWorker.observe(this){ workInfos ->
            if (workInfos.isNullOrEmpty()) return@observe
            val workInfo = workInfos[0]
            mWorkInfo = workInfo
            Log.d("TAG","worker state:${workInfo.state.name}")
            if (workInfo.state.isFinished){
                mBinding.goBtn.visibility = View.VISIBLE
                mBinding.cancelBtn.visibility = View.GONE
                mBinding.progressBar.visibility = View.GONE
            }else{
                mBinding.goBtn.visibility = View.GONE
                mBinding.cancelBtn.visibility = View.VISIBLE
                mBinding.progressBar.visibility = View.VISIBLE
            }
        }
    }

    private fun example(){
        val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
        val request = OneTimeWorkRequestBuilder<MyWorker>()
            .setConstraints(constraints).setInputData(Data.Builder().putString("param","我是参数").build())
            .build()
        WorkManager.getInstance().enqueue(request)

        WorkManager.getInstance().getWorkInfoByIdLiveData(request.id).observe(this, Observer {
            it?.let { workInfo ->
                when(it.state){
                    WorkInfo.State.SUCCEEDED -> {
                        val result = it.outputData.getString("result")
                        Toast.makeText(this,"执行成功${result}",Toast.LENGTH_SHORT).show()
                        Log.d("TAG","后台任务执行成功")
                    }
                    WorkInfo.State.BLOCKED -> {
                        Log.d("TAG","后台任务挂起")
                    }
                    WorkInfo.State.CANCELLED -> {
                        Log.d("TAG","后台任务取消")
                    }
                    WorkInfo.State.FAILED -> {
                        Log.d("TAG","后台任务失败")
                    }
                    WorkInfo.State.ENQUEUED -> {
                        Log.d("TAG","后台任务已运行")
                    }
                    WorkInfo.State.RUNNING -> {
                        Log.d("TAG","后台任务正在执行")
                    }

                }
            }
        })
    }

    //进程杀掉后，该任务会重新开始
    private fun doWorker(){
        val builder = OneTimeWorkRequestBuilder<NetWorker>()
            .addTag(WORKER_TAG)
            .setBackoffCriteria(BackoffPolicy.LINEAR,10L,TimeUnit.SECONDS)//重试策略，隔10秒重试一次
            .build()
        mWorkerManager
            .beginUniqueWork(WORKER_NAME,ExistingWorkPolicy.KEEP,builder)
            .enqueue()
    }

    private fun cancelWorker(){
        mWorkerManager.cancelUniqueWork(WORKER_NAME)
    }
}